package com.shensi.adminCollect.service.station.impl;

import com.alibaba.fastjson.JSONObject;
import com.shensi.common.core.constant.HttpStatus;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.adminCollect.mapper.coupon.CouponIssueRelationMapper;
import com.shensi.adminCollect.service.coupon.ICouponInfoService;
import com.shensi.adminCollect.domain.customer.dto.CustomerCardChangeDto;
import com.shensi.adminCollect.mapper.customer.CustomerCardSettingMapper;
import com.shensi.adminCollect.service.customer.ActivityMessagePushRecordService;
import com.shensi.adminCollect.service.customer.ICustomerCardUseRecordService;
import com.shensi.adminCollect.service.customer.ICustomerElectronicCardService;
import com.shensi.adminCollect.service.station.CouponActivityService;
import com.shensi.adminCollect.service.station.ElectronicCardService;
import com.shensi.adminCollect.service.system.IAppUserInfoUserService;
import com.shensi.adminCollect.service.system.ISysStationUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Random;

/**
 * @Auther: zxy
 * @Date: 2023/10/10 19:54
 * @Description:
 */
@Service
@Slf4j
public class ElectronicCardServiceImpl implements ElectronicCardService {

    @Resource
    private ICustomerCardUseRecordService customerCardUseRecordService;

    @Resource
    private IAppUserInfoUserService appUserInfoUserService;

    @Resource
    private ISysStationUserService sysStationUserService;

    @Resource
    private ICustomerElectronicCardService iCustomerElectronicCardService;

    @Resource
    private ICouponInfoService couponInfoService;

    @Resource
    private CouponActivityService couponActivityService;

    @Resource
    private CouponIssueRelationMapper couponIssueRelationMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ActivityMessagePushRecordService activityMessagePushRecordService;

    @Autowired
    private CustomerCardSettingMapper customerCardSettingMapper;

    @Value("${message.channel}")
    private String channel;

    @Value("${qujia.payBaseUrl}")
    private String payBaseUrl;

    @Autowired
    private RestTemplate restTemplate;


//    @Override
//    public AjaxResult updateUserReocrd(CustomerCardChangeDto customerCardChangeDto) {
//        CustomerElectronicCard customerElectronicCardRes = iCustomerElectronicCardService.selectCustomerElectronicCard(customerCardChangeDto.getId());
//
//        CustomerCardUseRecord customerCardUseRecord = new CustomerCardUseRecord();
//        customerCardUseRecord.setOrderNo(generateOrdNo());
//        customerCardUseRecord.setCustomerNo(customerElectronicCardRes.getCustomerNo());
//
//        Long stationId2 = customerElectronicCardRes.getStationId2();
//        if(Objects.nonNull(stationId2)){
//            customerCardUseRecord.setStationId(customerElectronicCardRes.getStationId2().intValue());
//        }else {
//            if(Objects.isNull(customerCardChangeDto.getStationId())){
//                return AjaxResult.error("请选择油站主体");
//            }
//            customerCardUseRecord.setStationId(customerCardChangeDto.getStationId().intValue());
//        }
//        if (Objects.isNull(customerCardUseRecord.getStationId())) {
//            return AjaxResult.error("请选择油站主体");
//        }
//        SysStationUser sysStationUser = sysStationUserService.selectSysStationUserById(Long.valueOf(customerCardUseRecord.getStationId()));
//        customerCardUseRecord.setEnterpriseId(sysStationUser.getEnterpriseId());
//
//        SysAppUserInfoUser sysAppUserInfoUser = new SysAppUserInfoUser();
//        sysAppUserInfoUser.setMobilePhone(customerElectronicCardRes.getMobilePhone());
//        sysAppUserInfoUser.setStationId(sysStationUser.getEnterpriseId());
//        SysAppUserInfoUser one = appUserInfoUserService.getOne(sysAppUserInfoUser);
//        if (one != null) {
//            customerCardUseRecord.setCustomerName(one.getBlogNickName());
//            customerCardUseRecord.setCustomerNo(one.getMemberCode());
//        }
//        BigDecimal afterAmt = customerCardChangeDto.getAmt();
//        BigDecimal beforeAmt = customerElectronicCardRes.getAmt();
//        //新的余额
//        BigDecimal amt = BigDecimal.ZERO;
//        Integer operateType = customerCardChangeDto.getOperateType();
//        if (operateType == 1){
//            if (beforeAmt.subtract(afterAmt).compareTo(BigDecimal.ZERO) < 0 ){
//                return AjaxResult.error("余额不够扣减");
//            }
//             amt = beforeAmt.subtract(afterAmt);
//        }else {
//            amt = beforeAmt.add(afterAmt);
//        }
//
//        customerCardUseRecord.setUsageType(operateType == 0 ? "+" : "-");
//        customerCardUseRecord.setPayType(operateType == 0? CardRecordType.MANUAL_ADD.getKey() : CardRecordType.MANUAL_SUB.getKey());
//        customerCardUseRecord.setCardOilsType(customerElectronicCardRes.getCardOilsType());
//        customerCardUseRecord.setAmt(afterAmt);
//        customerCardUseRecord.setBalance(amt);
//        customerCardUseRecord.setCreateTime(new Date());
//        customerCardUseRecord.setPresentAmt(BigDecimal.ZERO);
//        customerCardUseRecord.setMobilePhone(customerElectronicCardRes.getMobilePhone());
//        customerCardUseRecord.setStatus("1");
//        customerCardUseRecord.setReason(customerCardChangeDto.getReason());
//        LoginUser user = SecurityUtils.getLoginUser();
//        Integer userId=null;
//        if (user != null) {
//            userId = user.getUser().getUserId().intValue();
//        }
//        customerCardUseRecord.setOperator(userId);
//        customerCardUseRecordService.insertCustomerCardUseRecord(customerCardUseRecord);
//        //放入消息队列参与充值立减
//        if(operateType == 0){
//            //充值计算立减活动
//            activityMessagePushRecordService.sendWxMessage(ActivityMessagePushRecord.TOPIC_REDUCTION_ACTIVITY, JSON.toJSONString(customerCardUseRecord),WxConsumptionMessageEnum.RECHARGE_REDUCTION_ACTIVITY);
//        }
//
//
//        CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();
//        customerElectronicCard.setRecentlyTime(new Date());
//        customerElectronicCard.setId(customerCardChangeDto.getId());
//        customerElectronicCard.setAmt(amt);
//
//        iCustomerElectronicCardService.updateCustomerElectronicCard(customerElectronicCard);
//
//        CustomerCardSetting form = new CustomerCardSetting();
//        form.setEnterpriseId(customerCardUseRecord.getEnterpriseId());
//        CustomerCardSetting setting = customerCardSettingMapper.selectCustomerCardSetting(form);
//
//        if(setting != null && StringUtils.equals("1",setting.getManualChangeWxNotifyFlag())
//                && one != null && StringUtils.isNotBlank(one.getBlogOpenid())){
//            // 余额调整消息推送
//            BalanceChangeWxNotifyDTO notifyDTO = new BalanceChangeWxNotifyDTO();
//            notifyDTO.setEnterpriseId(customerCardUseRecord.getEnterpriseId().intValue());
//            notifyDTO.setOpenId(one.getBlogOpenid());
//            notifyDTO.setCustomerNo(one.getMemberCode());
//            if (StringUtils.equals(ElectricCardUsageTypeEnum.CONSUME.getKey(),customerCardUseRecord.getUsageType())) {
//                notifyDTO.setAmt(customerCardUseRecord.getAmt().negate());
//            }else{
//                notifyDTO.setAmt(customerCardUseRecord.getAmt());
//            }
//            notifyDTO.setPresentAmt(customerCardUseRecord.getPresentAmt());
//            notifyDTO.setBalance(customerCardUseRecord.getBalance());
//
//            UniversalRedisMessageDto messageDto = new UniversalRedisMessageDto();
//            messageDto.setData(JSONObject.toJSONString(notifyDTO));
//            messageDto.setMessageType(WxConsumptionMessageEnum.BALANCE_CHANGE_PUSH.getValue());
//            messageDto.setTitle("调整余额 推送公众号信息");
//            redisTemplate.convertAndSend(channel,JSONObject.toJSONString(messageDto));
//        }
//
//        // 发券
//        if (CollectionUtils.isNotEmpty(customerCardChangeDto.getCouponIds())) {
//
//                log.info("优惠券发放ids：{}", customerCardChangeDto.getCouponIds());
//                //调用发券接口
//                DrawCoupon drawCoupon = new DrawCoupon();
//                drawCoupon.setCouponIssueIdList(customerCardChangeDto.getCouponIds());
//                drawCoupon.setMobilePhoneList(Collections.singletonList(customerElectronicCardRes.getMobilePhone()));
//                drawCoupon.setEnterpriseId(sysStationUser.getEnterpriseId());
//                couponActivityService.sendCoupon(drawCoupon);
//
//                //todo 推送消息
//                Integer messagePush = customerCardChangeDto.getMessagePush();
//                if (messagePush == 1) {
//                    //todo 创建发送消息对象
//                    AdjustmentBalancePush balancePush = new AdjustmentBalancePush();
//                    balancePush.setCouponIds(customerCardChangeDto.getCouponIds());
//                    balancePush.setUserPhone(customerElectronicCardRes.getMobilePhone());
//                    balancePush.setStationId(customerElectronicCardRes.getStationId2());
//                    balancePush.setEnterpriseId(sysStationUser.getEnterpriseId());
//
//
//                    UniversalRedisMessageDto dto=new UniversalRedisMessageDto();
//                    dto.setData(JSONObject.toJSONString(balancePush));
//                    dto.setMessageType(WxConsumptionMessageEnum.PERSONAL_COUPON_ISSUANCE_PUSH.getValue());
//                    dto.setTitle("调整余额发送优惠券 推送公众号信息");
//                    String str=JSONObject.toJSONString(dto);
//                    redisTemplate.convertAndSend(channel, str);
//                }
//            }
//
//        return AjaxResult.success("调整余额成功");
//    }

    @Override
    //@Transactional
    public AjaxResult updateUserReocrd(CustomerCardChangeDto customerCardChangeDto){
        LoginUser user = SecurityUtils.getLoginUser();
        Integer userId=null;
        if (user != null) {
            userId = user.getUser().getUserId().intValue();
        }
        customerCardChangeDto.setOperator(userId);
        String s = restTemplate.postForObject(payBaseUrl+"/electronicCard/pcUpdateBalance", customerCardChangeDto, String.class, Collections.emptyMap());
        JSONObject jsonObject = JSONObject.parseObject(s);
        Integer retCode = jsonObject.getInteger("retCode");
        AjaxResult result;
        if (retCode != null) {
            if (retCode == 0) {
                result = new AjaxResult(HttpStatus.SUCCESS,jsonObject.getString("message"),jsonObject.get("data"));
            }else{
                result = new AjaxResult(retCode,jsonObject.getString("message"),jsonObject.get("data"));
            }
        }else{
            result = AjaxResult.error("服务异常");
        }
        return result;
    }

    private String generateOrdNo() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        String ordNo = System.currentTimeMillis() + result;
        return ordNo;
    }
}








